package com.wondertek.poms.init.service.impl;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wondertek.poms.common.constant.Constants;
import com.wondertek.poms.common.service.impl.ServiceImpl;
import com.wondertek.poms.common.utils.CopyUtils;
import com.wondertek.poms.common.utils.StringUtil;
import com.wondertek.poms.init.config.InitConstants;
import com.wondertek.poms.init.dao.IInitDataDao;
import com.wondertek.poms.init.dao.IInitDataHisDao;
import com.wondertek.poms.init.po.InitData;
import com.wondertek.poms.init.po.InitDataHis;
import com.wondertek.poms.init.service.IInitDataService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * <p><b>InitDataServiceImpl Description:</b> 初始化表 service层实现 </p>
 * @author 窦再兴
 * <p><b>DATE</b> 2020-03-30 18:57:15</p>
 */
@Service
@Scope("prototype")
@Transactional(readOnly = false)
@Slf4j
public class InitDataServiceImpl extends ServiceImpl<InitData, Long> implements IInitDataService {
	
	@Autowired
	private IInitDataHisDao initDataHisDao;
	@Autowired
	private IInitDataDao initDataDao;
	@PersistenceContext
    private EntityManager em;
	
	@Override
	public InitData deleteLogic(Long id) {
		return null;
	}

	@Override
	public InitData merge(InitData model) {
		InitData dbo = jpaRepository.getOne(model.getId());
		CopyUtils.copyProperties(model, dbo);
		return jpaRepository.save(dbo);
	}

	@Override
	@Async(value = "threadPoolD")
	public void process(InitData d) {
		ThreadUtil.sleep(RandomUtil.randomInt(300));
		// 1.解析contentid 计数
		String[] cs = d.getContentId().split(Constants.SYNC_CONTENT_SEPARATOR);
		InitConstants.CURR_NUM.addAndGet(cs.length);
		// 2.发送http请求；存库删库
		String returnStr = httpPost(InitConstants.MOMS_SYNC_URL, 
				getXml(d.getOperation(), d.getContentId(), 
						d.getStrategyCodes(), d.getPlatform(), 
						d.getIsMishitong()));
		if (StringUtil.isBlank(returnStr)) {
			return;
		}
		InitDataHis his = new InitDataHis();
		CopyUtils.copyProperties(d, his, "id");
		his.setOptTime(DateUtil.now());
		initDataHisDao.save(his);
		initDataDao.delete(d);
	    // 3.限速；
//		int milliseconds = InitConstants.MINUTE * 60 * 1000;
//		int sleepTime = milliseconds / InitConstants.ALL_NUM / InitConstants.THREAD_NUM;
	}
	
	public static void main(String[] args) {
		int num = 300;
		int milliseconds = InitConstants.MINUTE * 60 * 1000;
		int sleepTime = milliseconds / num / InitConstants.THREAD_NUM;
		System.out.println(sleepTime);
	}
	
	public static String httpPost(String url, String xml) {
		PostMethod method = new PostMethod(url);
		HttpClient httpClient = new HttpClient();
		try {
			HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
			managerParams.setConnectionTimeout(10000);
			managerParams.setSoTimeout(10000);
			StringRequestEntity entity = new StringRequestEntity(xml, "application/xml", "UTF-8");
			method.setRequestEntity(entity);
			int statusCode = httpClient.executeMethod(method);
			if (statusCode != HttpStatus.SC_OK) {
				log.error("HttpClient Error==[入参:" + xml + "][statusCode = " + statusCode + "]");
				return "";
			}
			InputStream in = method.getResponseBodyAsStream();
			StringBuffer sb = new StringBuffer();
			InputStreamReader isr = new InputStreamReader(in, "UTF-8");
			char[] b = new char[4096];
			for (int n; (n = isr.read(b)) != -1;) {
				sb.append(new String(b, 0, n));
			}
			String returnStr = sb.toString();
			return returnStr;
		} catch (Exception e) {
			log.error("====moms同步工具类的URL失败======" + xml, e);
		} finally {
			method.releaseConnection();
		}

		return "";
	}
	
	private String getXml(String operation, String contentIds, String strategyCodes,
				String platForm, String isMishitong) {
		StringBuffer sb = new StringBuffer();
		sb.append("<message module=\"SCSP\" version=\"1.1\">");
		sb.append("	<header action=\"REQUEST\" command=\"PRO_TO_CONTNET\"/>");
		sb.append("	<body>");
		sb.append("		<proToContent operation=\"" + operation + "\">");
		sb.append("			<platform>" + platForm + "</platform>");
		sb.append("			<contentId><![CDATA[" + contentIds + "]]></contentId>");
		sb.append("			<copyRightContentId>888</copyRightContentId>");
		sb.append("			<strategyCode><![CDATA[" + strategyCodes + "]]></strategyCode>");
		sb.append("			<isMishitong>" + isMishitong + "</isMishitong>");
		sb.append("		</proToContent>");
		sb.append("	</body>");
		sb.append("</message>");
		return sb.toString();
	}

	@Override
	@Transactional
	public Iterable<InitData> batchSaveAll(Iterable<InitData> entities) {
		String sql = "insert into init_data (access_platform_id, content_id, create_time, is_mishitong, operation, platform, strategy_codes) values (";
		Iterator<InitData> iterator = entities.iterator();
		int index = 0;
        while (iterator.hasNext()) {
        	InitData data = iterator.next();
        	sql += data.getAccessPlatformId() + ",'" + data.getContentId() + "','" + data.getCreateTime() + "','" + data.getIsMishitong() + "','" + 
        			data.getOperation() + "','" + data.getPlatform() + "','" + data.getStrategyCodes() + "'),(";
        }
        sql = sql.substring(0, sql.length() - 2);
        System.out.println(sql);
        em.createNativeQuery(sql).executeUpdate();
        return entities;
	}
	
	
}